---
title: useEffect
author:
  name: '@msyleung'
  url: 'https://twitter.com/msyleung'
---

import useEffect from '../../../examples/files/hooks/useEffect.js'
import useEffectWithNoDeps from '../../../examples/files/hooks/useEffectWithNoDeps.js'
import useEffectWithEmptyDeps from '../../../examples/files/hooks/useEffectWithEmptyDeps.js'

We use the `useEffect` hook to call functions with side effects within our components.

---

## API

The `useEffect` hook takes 2 arguments:

- `callback` - a function with side effects
- `dependencies` - an optional array containing dependency values

When our component function runs, the `callback` will be called if any `dependencies` have changed since the last time the component function ran.

---

## Example

In this example, we'll log to the console any time the `count` is a multiple of 3. The `callback` is called every time the `countEvery3` changes, since `countEvery3` is listed as a dependency.

<Example
  code={useEffect}
  console={{
    enabled: true,
    visible: true,
  }}
  playground={{ enabled: false }}
/>

---

## Undefined or empty dependency array

If the dependency array is empty or `undefined`, `useEffect` will have a different behavior.

- `[]` - the `callback` is called only once, right after the component renders for the first time
- `undefined` - the `callback` is called on _every_ component render (every time the component function runs)

---

### `undefined` dependencies

Here the dependency array is `undefined`, so our `callback` will run every time our component function runs, e.g. any time we click the button and `useState` tells our component to re-run.

<Example
  code={useEffectWithNoDeps}
  console={{
    enabled: true,
    visible: true,
  }}
  playground={{ enabled: false }}
/>

---

### Empty dependencies

Here the dependency array is empty, so our `callback` will only run once (and therefore only log one time).

<Example
  code={useEffectWithEmptyDeps}
  console={{
    enabled: true,
    visible: true,
  }}
  playground={{ enabled: false }}
/>
